package vip.xiaonuo.supplier.modular.base.stores.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNode;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.supplier.modular.base.stores.entity.SupplierStores;
import vip.xiaonuo.supplier.modular.base.stores.mapper.SupplierStoresMapper;
import vip.xiaonuo.supplier.modular.base.stores.param.SupplierStoresAddParam;
import vip.xiaonuo.supplier.modular.base.stores.param.SupplierStoresEditParam;
import vip.xiaonuo.supplier.modular.base.stores.param.SupplierStoresIdParam;
import vip.xiaonuo.supplier.modular.base.stores.param.SupplierStoresPageParam;
import vip.xiaonuo.supplier.modular.base.stores.service.SupplierStoresService;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 门店（仓库）信息Service接口实现类
 *
 * @author Mr.wu
 * @date  2025/03/15 18:35
 **/
@Service
public class SupplierStoresServiceImpl extends ServiceImpl<SupplierStoresMapper, SupplierStores> implements SupplierStoresService {

    @Override
    public Page<SupplierStores> page(SupplierStoresPageParam supplierStoresPageParam) {
        QueryWrapper<SupplierStores> queryWrapper = new QueryWrapper<SupplierStores>().checkSqlInjection();
        if(ObjectUtil.isNotEmpty(supplierStoresPageParam.getStoreName())) {
            queryWrapper.lambda().eq(SupplierStores::getStoreName, supplierStoresPageParam.getStoreName());
        }
        if(ObjectUtil.isNotEmpty(supplierStoresPageParam.getStoreAddress())) {
            queryWrapper.lambda().like(SupplierStores::getStoreAddress, supplierStoresPageParam.getStoreAddress());
        }
        //数据归属
        queryWrapper.lambda().eq(SupplierStores::getCompanyId, StpLoginUserUtil.getLoginUser().getCompanyId());
        //仅查询门店信息
        queryWrapper.lambda().eq(SupplierStores::getStoreType,"STORE");
        if(ObjectUtil.isAllNotEmpty(supplierStoresPageParam.getSortField(), supplierStoresPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(supplierStoresPageParam.getSortOrder());
            queryWrapper.orderBy(true, supplierStoresPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(supplierStoresPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(SupplierStores::getSortCode);
        }
        return this.page(CommonPageRequest.defaultPage(), queryWrapper);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(SupplierStoresAddParam supplierStoresAddParam) {
        SupplierStores supplierStores = BeanUtil.toBean(supplierStoresAddParam, SupplierStores.class);
        //数据归属
        supplierStores.setCompanyId(StpLoginUserUtil.getLoginUser().getCompanyId());
        //设置类型为门店
        supplierStores.setStoreType("STORE");
        supplierStores.setParentId("0");//顶级
        this.save(supplierStores);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(SupplierStoresEditParam supplierStoresEditParam) {
        SupplierStores supplierStores = this.queryEntity(supplierStoresEditParam.getId());
        BeanUtil.copyProperties(supplierStoresEditParam, supplierStores);
        this.updateById(supplierStores);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<SupplierStoresIdParam> supplierStoresIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(supplierStoresIdParamList, SupplierStoresIdParam::getId));
    }

    @Override
    public SupplierStores detail(SupplierStoresIdParam supplierStoresIdParam) {
        return this.queryEntity(supplierStoresIdParam.getId());
    }

    @Override
    public SupplierStores queryEntity(String id) {
        SupplierStores supplierStores = this.getById(id);
        if(ObjectUtil.isEmpty(supplierStores)) {
            throw new CommonException("门店（仓库）信息不存在，id值为：{}", id);
        }
        return supplierStores;
    }

    @Override
    public List<SupplierStores> storeslist(){
        QueryWrapper<SupplierStores> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("ID","STORE_NAME");
        return this.list(queryWrapper.lambda().eq(SupplierStores::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId()).eq(SupplierStores::getParentId,'0').eq(SupplierStores::getStoreType,"STORE"));
    }

    @Override
    public List<Tree<String>> storesTree() {
        // 获取本单位所有门店和仓库 Mr.wu 2024.10.19
        List<SupplierStores> allStoresList = this.list(new LambdaQueryWrapper<SupplierStores>().eq(SupplierStores::getCompanyId,StpLoginUserUtil.getLoginUser().getCompanyId()));
        List<TreeNode<String>> treeNodeList = allStoresList.stream().map(supplierStores ->
                        new TreeNode<>(supplierStores.getId(), supplierStores.getParentId(),
                                supplierStores.getStoreName(), supplierStores.getSortCode()).setExtra(JSONUtil.parseObj(supplierStores)))
                .collect(Collectors.toList());
        return TreeUtil.build(treeNodeList, "0");
    }
}
